import webapp2
import cgi
import datetime
import logging
from django.utils import simplejson

from models.beer import Beer
from models.kegdroid import KegDroid
from models.drinker import Drinker
from models.kegdroid import KegDroid
from commons import PickleProperty

################        
class KegDroidHandler(webapp2.RequestHandler):
    
    def post(self):

        ## NEED TO ADD A LOT OF ERROR CHECKING.
        kegdroid_name = cgi.escape(self.request.get('kegdroid_name'))
        android_id = cgi.escape(self.request.get('android_id'))
        if (kegdroid_name != '' and android_id != ''):

            lat = (cgi.escape(self.request.get('kegdroid_lat')))
            lon = (cgi.escape(self.request.get('kegdroid_lon')))
            ## 0 = Left and 1 = Right when facing KegDroid 
            beer_id_tap_zero = cgi.escape(self.request.get('beer_id_tap_zero'))
            beer_id_tap_one = cgi.escape(self.request.get('beer_id_tap_one'))
            volume_remaining_tap_zero = cgi.escape(self.request.get('volume_remaining_tap_zero'))
            volume_remaining_tap_one = cgi.escape(self.request.get('volume_remaining_tap_one'))
            number_drinks_poured = cgi.escape(self.request.get('number_drinks_poured'))
            volume_poured = cgi.escape(self.request.get('volume_poured'))
            last_beer = cgi.escape(self.request.get('last_beer'))
            last_drinker = cgi.escape(self.request.get('last_drinker'))
            kd = KegDroid.all().filter('android_id =', android_id).get()
            if (kd == None):
                kd = KegDroid()
                kd.android_id = android_id
            kd.name = kegdroid_name
            #kd.coordinates = db.GeoPt(lat=float(lat), lon=float(lon))
            kd.lat = float(lat)
            kd.lon = float(lon)
            if (beer_id_tap_zero != ''):
                kd.beer_id_tap_zero = int(beer_id_tap_zero)
                if (not (beer_id_tap_zero in kd.unique_beers)):
                    kd.unique_beers.append(beer_id_tap_zero)
                    kd.unique_beer_count = len(kd.unique_beers)
            if (beer_id_tap_one != ''):
                kd.beer_id_tap_one = int(beer_id_tap_one)
                if (not (beer_id_tap_one in kd.unique_beers)):
                    kd.unique_beers.append(beer_id_tap_one)
                    kd.unique_beer_count = len(kd.unique_beers)
            if (number_drinks_poured !=''):
                kd.number_drinks_poured = int(number_drinks_poured)
            if (volume_poured !=''):
                kd.total_volume_poured = float(volume_poured)
            if (volume_remaining_tap_zero !=''):
                kd.volume_remaining_tap_zero = float(volume_remaining_tap_zero)
            if (volume_remaining_tap_one !=''):
                kd.volume_remaining_tap_one = float(volume_remaining_tap_one)
            if (last_beer !=''):
                kd.last_beer = int(last_beer)
            if (last_drinker !=''):
                kd.last_drinker =  int(last_drinker)
            kd.put()
            newkd = KegDroid.all().filter('name =', kegdroid_name).get()
            kdid = newkd.key().id()
            self.redirect('/kegdroids?id=' + str(kdid))
            
        else:
            if (kegdroid_name == ''):
                self.response.out.write("<html><body><p>Missing name for KegDroid</p></body></html>")
            elif (android_id == ''):
                self.response.out.write("<html><body><p>Missing Android Id</p></body></html>")
            else: 
                self.response.out.write("<html><body><p>An Error Occured</p></body></html>")
    
    def get(self):
        tag = self.request.get('id')
        if (tag):
            if (tag == "all"):
                output = []
                kegdroids = KegDroid.all().order('name')
                for kd in kegdroids:
                    output.append(kd.to_dict())
                self.response.out.write(simplejson.dumps({'kegdroids': output}).replace("\/", "/"))
            else:
                output = []
                kId = int(tag)
                if (kId > 0):
                    kd = KegDroid.get_by_id(kId)
                    if kd != None:
                        output.append(kd.to_dict()) 
                self.response.out.write(simplejson.dumps({'kegdroid': output}).replace("\/", "/"))
        else :
            
            output = []
            kegdroids = KegDroid.all().order('name')
            for kd in kegdroids:
                output.append(kd.to_dict())
            self.response.out.write(simplejson.dumps({'kegdroids': output}).replace("\/", "/"))

################        
class AddKegDroidHandler(webapp2.RequestHandler):

    def get(self):
        beer_list = '<option selected="selected" value="">---------</option>'
        beers = Beer.all().order('name')
        for br in beers:
            beer_list += '<option value=" '
            beer_list += str(br.key().id())
            beer_list += ' \"> '
            beer_list += br.name
            beer_list += ' </option> '

        
        self.response.out.write("""
                <html>
                <body>
            """)
        self.response.out.write( """
            <script src="http://code.jquery.com/jquery-1.8.3.min.js">
            </script>

            <SCRIPT LANGUAGE="javascript">
            $(document).ready(function() {
                $('#beer_beer_id_tap_zero').change(function() {
                    $('input[name="selected_beer_zero"]').val($(this).val());
                });
            });
            </SCRIPT>
            <SCRIPT LANGUAGE="javascript">
            $(document).ready(function() {
                $('#beer_beer_id_tap_one').change(function() {
                    $('input[name="selected_beer_one"]').val($(this).val());
                });
            });
            </SCRIPT>
            """ )   
        ## SHOULD THE BEERS BE DROPDOWN SELECTION?
        self.response.out.write("""
            <form action="/kegdroids" method="post">
            <div>KegDroid Name: <input type="text" name="kegdroid_name" /></div>
            <div>Android Id: <input type="text" name="android_id" /></div> """)
            
        self.response.out.write("""<div>Beer on Tap Zero <select id="beer_beer_id_tap_zero" > """)
        self.response.out.write(beer_list)
        self.response.out.write('</select> ')
        self.response.out.write(""" <input type="text" name="selected_beer_zero" size="3" /> 
                </div> """)
                
        self.response.out.write("""<div>Beer on Tap One <select id="beer_beer_id_tap_one" > """)
        self.response.out.write(beer_list)
        self.response.out.write('</select> ')
        self.response.out.write(""" <input type="text" name="selected_beer_one" size="3" /> 
                </div> """)
        self.response.out.write("""
            <div>Last Drinker <input type="text" name="last_drinker" /></div>
            <div>Last Beer <input type="text" name="last_beer" /></div>
            <div>Total Volume Poured <input type="text" name="volume_poured" /></div>
            <div>Number Drinks Poured <input type="text" name="number_drinks_poured" /></div> 
            <div>Latitude <input type="text" name="kegdroid_lat" /></div>
            <div>Longitude <input type="text" name="kegdroid_lon" /></div>
            """)
            
        self.response.out.write("""<div><input type="submit" value="Create KegDroid"></div>
            </form>""")
        self.response.out.write('</body></html>')

#################
class KegDroidCheckDrinkerHandler(webapp2.RequestHandler):

    def get(self):
        tag = self.request.get('gplusid')
        logging.info("gplusid submitted")
        logging.info(tag)
        if (tag):
            output = []
            kegdroids = KegDroid.all()
            for kd in kegdroids:
                logging.info(kd.to_dict())
                logging.info(kd.authorized_drinkers)
                if (tag in kd.authorized_drinkers):

                    output.append(kd.to_dict())
            self.response.out.write(simplejson.dumps({'kegdroids' : output}).replace("\/", "/"))



################        
class AddKegDroidDrinkerHandler(webapp2.RequestHandler):

    def post(self):
        android_id = cgi.escape(self.request.get('android_id')).strip()
        logging.info("android id ")
        logging.info(android_id)
        gplus_id = cgi.escape(self.request.get('gplus_id'))
        if (android_id != ''):
            kd = KegDroid.all().filter("android_id", android_id).get()
            logging.info("kd:")
            logging.info(kd.name)
            logging.info(kd.android_id)
            logging.info(kd.authorized_drinkers)
            #add checking of gplusid format - eventually do a look up to verify
            if (gplus_id != ''):
                logging.info("Good gplus_id")
                logging.info(gplus_id)
                #FOR LOGGING ONLY
                for t in kd.authorized_drinkers:
                    logging.info("t")
                    logging.info(t)
                if (not(gplus_id in kd.authorized_drinkers)):
                    logging.info("appending")
                    kd.authorized_drinkers.append(gplus_id)
                logging.info("END current drinkers")
            logging.info(len(kd.authorized_drinkers))       
            kd.number_drinkers_authorized = len(kd.authorized_drinkers)
            kd.put()
            newkd = KegDroid.all().filter('android_id', android_id).get()
            kdid = newkd.key().id()
            self.redirect('/kegdroids?id=' + str(kdid))

    def get(self):

        logging.info("Adding Drinker")

        kegdroid_list = '<option selected="selected" value="">---------</option>'
        kegdroids = KegDroid.all().order('name')
        for kd in kegdroids:
            kegdroid_list += '<option value=" '
            kegdroid_list += str(kd.android_id)
            kegdroid_list += ' \"> '
            kegdroid_list += kd.name
            kegdroid_list += ' </option> '

        self.response.out.write("""
                <html>
                <body>
            """)
        self.response.out.write( """
            <script src="http://code.jquery.com/jquery-1.8.3.min.js">
            </script>

            <SCRIPT LANGUAGE="javascript">
            $(document).ready(function() {
                $('#kegdroid').change(function() {
                    $('input[name="android_id"]').val($(this).val());
                });
            });
            </SCRIPT>
            """ )   
        ## SHOULD THE BEERS BE DROPDOWN SELECTION?
        self.response.out.write("""
            <form action="/kegdroids/adddrinker" method="post">
            <div>Drinker GPlus ID: <input type="text" name="gplus_id" /></div>""")
            
        self.response.out.write("""<div>KegDroids <select id="kegdroid" > """)
        self.response.out.write(kegdroid_list)
        self.response.out.write('</select> ')
        self.response.out.write(""" <input type="text" name="android_id" size="3" /> 
                </div> """)
            
        self.response.out.write("""<div><input type="submit" value="Add Drinker"></div>
            </form>""")
        self.response.out.write('</body></html>')


################        
class RegisterKegDroidHandler(webapp2.RequestHandler):
    
    def post(self):

        ## NEED TO ADD A LOT OF ERROR CHECKING.
        kegdroid_name = cgi.escape(self.request.get('kegdroid_name'))
        android_id = cgi.escape(self.request.get('android_id'))
        if (kegdroid_name != '' and android_id != ''):
            kd = KegDroid.all().filter('android_id =', android_id).get()
            if (kd == None):
                kd = KegDroid()
                kd.android_id = android_id
            kd.name = kegdroid_name         
            kd.put()
            newkd = KegDroid.all().filter('name =', kegdroid_name).get()
            kdid = newkd.key().id()
            self.redirect('/kegdroids?id=' + str(kdid))
            
        else:
            if (kegdroid_name == ''):
                self.response.out.write("<html><body><p>Missing name for KegDroid</p></body></html>")
            elif (android_id == ''):
                self.response.out.write("<html><body><p>Missing Android Id</p></body></html>")
            else: 
                self.response.out.write("<html><body><p>An Error Occured</p></body></html>")
    
                    
app = webapp2.WSGIApplication([
    ('/kegdroids/add', AddKegDroidHandler),
    ('/kegdroids/adddrinker', AddKegDroidDrinkerHandler),
    ('/kegdroids/checkdrinker', KegDroidCheckDrinkerHandler),
    ('/kegdroids/register', RegisterKegDroidHandler),
    ('/kegdroids', KegDroidHandler)
   
], debug=True)


     